package com.example.demo.service.impl;


import com.example.demo.commen.ResultCode;
import com.example.demo.dao.ArticleMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.Article;
import com.example.demo.model.Board;
import com.example.demo.model.User;
import com.example.demo.service.IArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    BoardServiceImpl boardService;
    @Autowired
    UserServiceImpl userService;
    @Override
    public void insertArticle(Article article) {

        if(article==null||!StringUtils.hasLength(article.getContent())||
                !StringUtils.hasLength(article.getTitle())
              ||article.getBoardId()==null){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }

        System.out.println("abcdefg");

        //设置一些值
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte)0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
       int flag = articleMapper.insertSelective(article);

        if(flag!=1){
            throw new ApplicationException(ResultCode.FAILED.getMessage());
        }

        //发布帖子后，得更新用户表和版块表的帖子数量
          Long userId = article.getUserId();
        Long boardId = article.getBoardId();
        if(userId==null||userId<=0||boardId==null||boardId<=0){
            throw  new ApplicationException("根据插入帖子查询的用户Id或版块Id为空");
        }
        userService.addOneArticleById(userId);  //如果这个抛出异常，那就会发生回滚
        boardService.addOneArticleById(boardId);//如果这个抛出异常，那就会发生回滚
        log.info("发送帖子成功");
    }

    @Override
    public List<Article> selectAll() {

        List<Article> lists = articleMapper.selectAll();
        return lists;
    }

    @Override
    public List<Article> selectMatchAllByBoardId(Long boardId) {
        if(boardId==null||boardId<=0){
            throw new ApplicationException("帖子接口-参数传入错误");
        }
        Board board = boardService.selectById(boardId);
        if(board==null){
            throw  new ApplicationException("版块不存在-显示不了");
        }
       List<Article> lists =  articleMapper.selectMatchAllByBoardId(boardId);
        if(lists==null){
          lists = new ArrayList<>();
        }
        return  lists;
    }

    @Override
    public Board selectBoardById(Long boardId) {
          if(boardId==null||boardId<=0){
              throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
          }

       Board board = boardService.selectById(boardId);
          if(board==null||board.getDeleteState()==1){
              throw new ApplicationException("查询版块不存在");
          }
          return board;
    }

    @Override
    public Article   selectDetailByArticleId(Long id) {
        if(id==null||id<=0){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());

        }
       Article article= articleMapper.selectArticleById(id);
        if(article==null){
            throw new ApplicationException("该帖子详情查询失败--请联系管理员");
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);
      int row =  articleMapper.updateByPrimaryKeySelective(updateArticle);
      if(row!=1){
          throw  new ApplicationException(ResultCode.FAILED.toString());
      }
       article = articleMapper.selectArticleById(article.getId());
      return  article;
    }

    @Override
    public void updateArticleDetail(Article article) {
             if(article==null||article.getId()<=0){
                 throw new ApplicationException("帖子不存在");
             }

             Article newArticle = articleMapper.selectByPrimaryKey(article.getId());
             newArticle.setId(article.getId());
             newArticle.setTitle(article.getTitle());
             newArticle.setContent(article.getContent());
           Integer flag =  articleMapper.updateByPrimaryKeySelective(newArticle);
           if(flag!=1){
               throw new ApplicationException(ResultCode.FAILED.toString());
           }

         }

    @Override
    public Article updateArticleAdmiration(Long id) {
        if(id==null||id<=0){
            throw  new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }

        Article article = articleMapper.selectArticleById(id);
        if(article==null||article.getId()<=0){
            throw new ApplicationException("帖子不存在-点赞功能");
        }
        article.setLikeCount(article.getLikeCount()+1);
      int flag = articleMapper.updateByPrimaryKeySelective(article);
      if(flag!=1){
          throw  new ApplicationException("更新失败");
      }
        log.info("帖子经过点赞后为"+article.getLikeCount());

        return article;
    }

    @Override
    public void deleteArticleById(Long id) {
        if(id==null||id<=0){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }

        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null||article.getUserId()<=0||article.getDeleteState()==1){
            throw new ApplicationException("帖子不存在或者该帖子已被删除");
        }

        article.setDeleteState((byte)1);
        Date date = new Date();
        article.setUpdateTime(date);
        int flag = articleMapper.updateByPrimaryKeySelective(article);
        if(flag!=1){
            throw new ApplicationException("删除失败");
        }
       userService.subOneArticleById(article.getUserId());
        boardService.subOneArticleById(article.getBoardId());


    }

    @Override
    public Article selectArticleById(Long id) {
        if(id==null||id<=0){
            throw  new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null||article.getUserId()<=0||article.getDeleteState()==1){
            throw new ApplicationException("帖子不存在");
        }
        return article;
    }

    @Override
    public void addOneReplyCountById(Long id) {
        if(id==null||id<=0){
            log.info("参数异常");
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null||article.getState()==1||article.getDeleteState()==1){
            log.info("帖子状态异常");
            throw new ApplicationException("帖子状态异常");
        }
        article.setReplyCount(article.getReplyCount()+1);
        article.setUpdateTime(new Date());
       int flag = articleMapper.updateByPrimaryKeySelective(article);
       if(flag!=1){
           throw new ApplicationException(ResultCode.FAILED.toString());
       }
    }

    @Override
    public List<Article> selectArticleByUserId(Long userId) {
        if(userId==null||userId<=0){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        User user = userService.getUserById(userId);
        if(user==null||user.getId()<=0){
            throw new ApplicationException("用户不存在");
        }
        List<Article> list = articleMapper.selectArticleByUserId(userId);
        return list;

    }
}
